var buket = 'http://image.hngpmall.com/';
$(function () {
    $('.modal').on('hide.bs.modal', function () {
        $('#page-wrapper > .wrapper-content').removeClass('fadeInRight');
    });
});

//清除seller缓存
function clearCache() {
    $.ajax({
        type: 'POST',
        url: "/seller/api/clear_cache",
        success: function (data) {
            easyshow('页面缓存已清除成功');
        },
        error: function (xhr, type) {
            easyshow('操作失败');
        }
    });
}


// 高级搜索边栏动画
jQuery.gjSearch = function (right) {
    $('#searchBarOpen').click(function () {
        $('.search-gao-list').animate({'right': '-40px'}, 200,
            function () {
                $('.search-gao-bar').animate({'right': '0'}, 300);
            });
    });
    $('#searchBarClose').click(function () {
        $('.search-gao-bar').animate({'right': right}, 300,
            function () {
                $('.search-gao-list').animate({'right': '0'}, 200);
            });
    });
};

/////////////////////////////
/////   FIXME 新增      /////
////////////////////////////
function clickEdit(obj, param, callback) {
    var tag = obj.firstChild.tagName;

    if (typeof (tag) != "undefined" && tag.toLowerCase() == "input") {
        return;
    }

    /* 保存原始的内容 */
    var org = obj.innerHTML;
    var val = window.ActiveXObject ? obj.innerText : obj.textContent;

    /* 创建一个输入框 */
    var txt = document.createElement("INPUT");
    txt.value = (val == 'N/A') ? '' : val;
    txt.className = 'text textpadd';
    if (obj.offsetWidth > 12) {
        txt.style.width = (obj.offsetWidth - 12) + "px";
    } else {
        txt.style.width = obj.offsetWidth + "px";
    }
    if ($(obj).siblings(".edit_icon")) {
        $(obj).siblings(".edit_icon").hide();
    }
    /* 隐藏对象中的内容，并将输入框加入到对象中 */
    obj.innerHTML = "";
    obj.appendChild(txt);
    txt.focus();

    /* 编辑区输入事件处理函数 */
    txt.onkeypress = function (e) {
        var evt = (typeof e == "undefined") ? window.event : e;
        var obj = document.all ? evt.srcElement : evt.target;

        if (evt.keyCode == 13) {
            obj.blur();
            return false;
        }

        if (evt.keyCode == 27) {
            obj.parentNode.innerHTML = org;
        }
    };

    txt.onblur = function (e) {
        if (trim(txt.value).length > 0 && txt.value != org) {
            if (typeof callback == 'function') {
                param.value = txt.value;
                callback(param, function (res) {
                    if (res.msg) {
                        layer.msg(res.msg, {time: 2000});
                    }
                    obj.innerHTML = (res.msg) ? org : res.content;
                });
            }
        } else {
            obj.innerHTML = org;
        }
    };
}

function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    var strValue = "";
    if (r != null) {
        strValue = unescape(r[2]);
    }
    return strValue;
}

function single_upload(file, complete, error, token) {
    if (file) {
        var key = (new Date()).valueOf().toString() + Math.random().toString().slice(2, 8);
        var ear = file.name.substr(file.name.lastIndexOf('.'));//后缀名

        var ossData = new FormData();
        ossData.append('OSSAccessKeyId', token.accessid);
        ossData.append('policy', token.policy);
        ossData.append('Signature', token.signature);
        ossData.append('key', token.dir + key + ear);
        ossData.append('success_action_status', 201);
        ossData.append('file', file);//必须是表单中的最后一个域

        $.ajax({
            url: token.url,
            data: ossData,
            dataType: 'xml',
            processData: false,
            contentType: false,
            type: 'POST',
            success: function (data) {
                complete($(data).find('Location').text());
            },
            error: function (xhr) {
                if (typeof error == 'function') {
                    error(xhr);
                } else {
                    console.log(xhr);
                    if (layer) {
                        layer.close(index);
                        layer.msg('上传失败');
                    } else {
                        alert('上传失败');
                    }
                }
            }
        });
    } else {
        if (typeof error == 'function') {
            error(xhr);
        } else {
            console.log(xhr);
            if (layer) {
                layer.close(index);
                layer.msg('上传失败');
            } else {
                alert('上传失败');
            }
        }
    }
}

function checkMobile(no) {
    no = no + '';
    return (no.length == 11 && /^(((13[0-9]{1})|(14[0-9]{1})|(15[0-9]{1})|(16[0-9]{1})|(17[0-9]{1})|(18[0-9]{1})|(19[0-9]{1}))+\d{8})$/.test(no));
}

function convertCurrency(money) {
    //汉字的数字
    var cnNums = new Array('零', '壹', '贰', '叁', '肆', '伍', '陆', '柒', '捌', '玖');
    //基本单位
    var cnIntRadice = new Array('', '拾', '佰', '仟');
    //对应整数部分扩展单位
    var cnIntUnits = new Array('', '万', '亿', '兆');
    //对应小数部分单位
    var cnDecUnits = new Array('角', '分', '毫', '厘');
    //整数金额时后面跟的字符
    var cnInteger = '整';
    //整型完以后的单位
    var cnIntLast = '元';
    //最大处理的数字
    var maxNum = 999999999999999.9999;
    //金额整数部分
    var integerNum;
    //金额小数部分
    var decimalNum;
    //输出的中文金额字符串
    var chineseStr = '';
    //分离金额后用的数组，预定义
    var parts;
    if (money === '') { //不能用==
        return '';
    }
    money = parseFloat(money);
    if (money >= maxNum) {
        //超出最大处理数字
        return '';
    }
    if (money == 0) {
        chineseStr = cnNums[0] + cnIntLast + cnInteger;
        return chineseStr;
    }
    //转换为字符串
    money = money.toString();
    if (money.indexOf('.') == -1) {
        integerNum = money;
        decimalNum = '';
    } else {
        parts = money.split('.');
        integerNum = parts[0];
        decimalNum = parts[1].substr(0, 4);
    }
    //获取整型部分转换
    if (parseInt(integerNum, 10) > 0) {
        var zeroCount = 0;
        var IntLen = integerNum.length;
        for (var i = 0; i < IntLen; i++) {
            var n = integerNum.substr(i, 1);
            var p = IntLen - i - 1;
            var q = p / 4;
            var m = p % 4;
            if (n == '0') {
                zeroCount++;
            } else {
                if (zeroCount > 0) {
                    chineseStr += cnNums[0];
                }
                //归零
                zeroCount = 0;
                chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
            }
            if (m == 0 && zeroCount < 4) {
                chineseStr += cnIntUnits[q];
            }
        }
        chineseStr += cnIntLast;
    }
    //小数部分
    if (decimalNum != '') {
        var decLen = decimalNum.length;
        for (var i = 0; i < decLen; i++) {
            var n = decimalNum.substr(i, 1);
            if (n != '0') {
                chineseStr += cnNums[Number(n)] + cnDecUnits[i];
            }
        }
    }
    if (chineseStr == '') {
        chineseStr += cnNums[0] + cnIntLast + cnInteger;
    } else if (decimalNum == '') {
        chineseStr += cnInteger;
    }
    return chineseStr;
}

function advisory() {
    $.ajax({
        type: 'POST',
        url: '/sp/index/advisory',
        success: function (data) {

            let url = 'http://zixun.hngpmall.com/backofficer.php?username=' +
                encodeURIComponent(data.username) +
                '&nickname=' +
                encodeURIComponent(data.nickname) +
                '&groupname=' +
                encodeURIComponent(data.groupname) +
                '&token=' + data.zixunToken;
            window.open(url);
        },
        error: function (xhr, type) {
            toastr.error(xhr.responseJSON);
        }
    });
}

function jumpCrm() {
    $.ajax({
        type: 'POST',
        url: '/sp/index/jumpCrm',
        success: function (data) {
            let url = 'http://crm.hngpmall.com/#/mutlogin?auth=' + data;
            window.open(url);
        },
        error: function (xhr, type) {
            toastr.error(xhr.responseJSON);
        }
    });
}

function preview() {
    $('.links').unbind('click').bind('click', function (event) {
        event = event || window.event;
        var target = event.target || event.srcElement,
            link = target.src ? target.parentNode : target,
            options = {index: link, event: event},
            links = this.getElementsByTagName('a');
        blueimp.Gallery(links, options);
    });
}

function uniqueCode(obj) {
    let param = $(obj).parent().data();
    vm.param = param;
    $.ajax({
        type: 'GET',
        url: '/sp/order/uniqueCode',
        data: param,
        success: function (data) {
            if (parseInt(param.ordersign)) {
                for (let i = data.length; i < obj.dataset.sl; i++) {
                    data.push({sn: '', img: '/public/static/images/update_images.jpg'});
                }
                vm.list = data;
                $('#unique-code-modal').modal('show');

            } else if (data.length == 0) {
                toastr.warning('订单已签收，此商品未上传唯一识别码');
                return;
            } else {
                vm.list = data;
                $('#unique-code-modal').modal('show');
            }
        },
        error: function (xhr, type) {
            toastr.error(xhr.responseJSON);
        }
    });
}

